<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\AppUsers;
use App\Models\Order;
use App\Models\Product;
use App\Models\Vpn;
use Carbon\Carbon;
use Illuminate\Http\Request;

class UserController extends Controller
{
    public function index(Request $request)
    {
        $token         = request()->post('token', '');
        $uuid          = request()->post('uuid', '');
        $user          = AppUsers::with(['level'])->where('api_token', $token)->where('uuid', $uuid)->first();
        $expires       = Carbon::parse($user->expires);
        $now           = Carbon::now();
        $user->minutes = !$expires->greaterThan($now) ? 0 : $now->diffInMinutes($expires);
        return $this->success(200, '成功', $user->toArray());
    }

    public function orders()
    {
        $token  = request()->post('token', '');
        $uuid   = request()->post('uuid', '');
        $user   = AppUsers::with(['level'])->where('api_token', $token)->where('uuid', $uuid)->first();
        $orders = Order::with(['product' => function ($query) {
            $query->select(['id', 'name', 'price', 'original']);
        }])->where(['admin_id' => $user->id])->get();

        return $this->success(200, '成功', $orders->toArray());
    }

    public function changePassword(Request $request)
    {
        $token = request()->post('token', '');
        $uuid  = request()->post('uuid', '');
        $user  = AppUsers::where('api_token', $token)->where('uuid', $uuid)->first();
        if (!$request->post('password', '')) {
            return $this->errors('-1', '请输入密码');
        }

        if ($request->post('password', '') !== $request->post('password_confirmation')) {
            return $this->errors('-1', '两次密码不一致');
        }

        $user->password = bcrypt($request->post('password'));
        if ($user->save()) {
            return $this->success(200, '修改成功', $user->toArray());
        }
        return $this->errors('-1', '修改失败');
    }

}
